<template>
  <div class="app-container">
    <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <div class="head-container">
        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
    </el-col>
    <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="发布时间">
            <el-date-picker
              v-model="daterangeReleaseTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="状态" clearable>
          <el-option
            v-for="dict in dict.type.tb_column_detail_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-select v-model="queryParams.isTop" placeholder="是否置顶" clearable>
          <el-option
            v-for="dict in dict.type.tb_top_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐" prop="isShare">
        <el-select v-model="queryParams.isShare" placeholder="是否推荐" clearable>
          <el-option
            v-for="dict in dict.type.tb_top_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['business:columnDetail:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['business:columnDetail:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['business:columnDetail:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['business:columnDetail:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="columnDetailList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="标题" align="left" prop="title" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="文章id" align="center" prop="detailId" />
           -->
           <el-table-column label="所属栏目" align="left" prop="columnName" :show-overflow-tooltip="true"/>
          <el-table-column label="发布时间" align="center" prop="releaseTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="文章来源" align="center" prop="comeForm" />
          <el-table-column label="是否置顶" align="center" prop="isTop" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.tb_top_state" :value="scope.row.isTop"/>
            </template>
          </el-table-column>
          <el-table-column label="是否推荐" align="center" prop="isShare" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.tb_top_state" :value="scope.row.isShare"/>
            </template>
          </el-table-column>
          <el-table-column label="阅读量" align="center" prop="clickNum" />
          <el-table-column label="状态" align="center" prop="state">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.tb_column_detail_state" :value="scope.row.state"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:columnDetail:edit']"
              >修改</el-button>
              <el-button v-if="scope.row.state == 'N'"
                size="mini"
                type="text"
                icon="el-icon-s-claim"
                @click="handleUpdateState(scope.row, 0)"
                v-hasPermi="['business:columnDetail:edit']"
              >发布</el-button>
              <el-button v-if="scope.row.state == 'Y'"
                size="mini"
                type="text"
                icon="el-icon-s-release"
                @click="handleUpdateState(scope.row, 1)"
                v-hasPermi="['business:columnDetail:edit']"
              >下架</el-button>
              <el-button v-if="scope.row.state != 'B' && scope.row.isShare == 0"
                size="mini"
                type="text"
                icon="el-icon-s-release"
                @click="handleUpdateShare(scope.row)"
                 v-hasRole="['admin']"
              >推荐</el-button>
              <el-button v-else-if="scope.row.state != 'B' && scope.row.isShare == 1"
                size="mini"
                type="text"
                icon="el-icon-s-release"
                @click="handleUpdateShare(scope.row)"
                 v-hasRole="['admin']"
              >取消推荐</el-button>
              <el-button v-if="scope.row.state != 'B' && scope.row.collectFlag == -1"
                size="mini"
                type="text"
                icon="el-icon-s-release"
                @click="collect(scope.row)"
              >收藏</el-button>
              <el-button v-if="scope.row.state != 'B' && scope.row.collectFlag != -1"
                size="mini"
                type="text"
                icon="el-icon-s-release"
                @click="collectDel(scope.row)"
              >取消收藏</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:columnDetail:remove']"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleReview(scope.row)"
              >评论</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
    </el-col>
    </el-row>


    <!-- 添加或修改文章内容详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属栏目" prop="columnId">
              <treeselect v-model="form.columnId" disabled :options="deptOptions" :show-count="true" placeholder="请选择所属栏目" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="releaseTime">
              <el-date-picker clearable
                v-model="form.releaseTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章来源" prop="comeForm">
              <el-input v-model="form.comeForm" placeholder="请输入文章来源" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否置顶" prop="isTop">
              <el-radio-group v-model="form.isTop">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="form.state">
                <el-radio label="N">草稿</el-radio>
                <el-radio label="Y">发布</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isPicCloumn == 'N'">
          <el-col :span="12">
            <el-form-item label="是否轮播图" prop="isLbt">
              <el-radio-group v-model="form.isLbt">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导航图片" prop="picPath">
              <imgageUpload v-model="form.picPath" :limit="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isPicCloumn == 'N'">
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isPicCloumn == 'Y'">
          <el-col :span="24">
            <el-form-item label="图片集合" prop="picContent">
              <imgageUpload v-model="form.picContent" :limit="20"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listColumnDetail, getColumnDetail, delColumnDetail, addColumnDetail, updateColumnDetail,columnTree } from "@/api/business/columnDetail";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { parseTime } from "@/utils/ruoyi"
import imgageUpload from '@/components/ImageUpload/index';
import { delUserCollect, addUserCollect } from "@/api/business/userCollect";

export default {
  name: "ColumnDetail",
  components: { Treeselect, imgageUpload },
  dicts: ['tb_column_detail_state', 'tb_top_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章内容详情表格数据
      columnDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标志时间范围
      daterangeReleaseTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        columnId: null,
        title: null,
        releaseTime: null,
        userId: null,
        isTop: null,
        isShare: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      columnId: null,
      isPicCloumn: 'N'
    };
  },
  watch: {
    '$route.query': 'initData'
  },
  created() {
    this.initData();
  },
  methods: {
    handleReview(row){
      this.$router.push({
        path: "/detailReview/index",
        query: { detailId: row.detailId },
      });
    },
    collect(row){
      addUserCollect({detailId: row.detailId}).then(res => {
        this.handleQuery();
        this.$modal.msg('收藏成功！')
      })
    },
    collectDel(row){
      delUserCollect(row.detailId).then(res => {
        this.handleQuery();
        this.$modal.msg('取消收藏成功！')
      })
    },
    initData(){
        const that = this;
        let data = this.$route.query;
        let date = parseTime(new Date(), '{y}-{m}-{d}')
        this.daterangeReleaseTime = [];
        this.daterangeReleaseTime.push(date)
        this.daterangeReleaseTime.push(date)
        this.getDeptTree();
        if(this.$store.state.user.id != 1){
          this.queryParams.userId = this.$store.state.user.id
        }
        if(data.columnId != undefined && data.columnId != this.columnId){
          that.columnId = data.columnId
          this.queryParams.columnId = data.columnId;
          that.isPicCloumn = data.isPic
        }
        this.handleQuery();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      columnTree().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.columnId = data.id;
      this.isPicCloumn = data.isPic
      this.handleQuery();
    },
    /** 查询文章内容详情列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeReleaseTime && '' != this.daterangeReleaseTime) {
        this.queryParams.params["beginReleaseTime"] = this.daterangeReleaseTime[0];
        this.queryParams.params["endReleaseTime"] = this.daterangeReleaseTime[1];
      }
      listColumnDetail(this.queryParams).then(response => {
        this.columnDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        detailId: null,
        columnId: this.queryParams.columnId != null ? this.queryParams.columnId : null,
        title: null,
        picPath: null,
        content: null,
        picContent: null,
        releaseTime: parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
        comeForm: this.$store.state.user.name,
        isTop: '0',
        isShare: '0',
        state: 'N',
        isLbt: '0',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeReleaseTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.detailId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章内容详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const detailId = row.detailId || this.ids
      getColumnDetail(detailId).then(response => {
        this.form = response.data;
        this.form.isTop += ''
        this.form.isShare += ''
        this.form.isLbt += ''
        this.open = true;
        this.title = "修改文章内容详情";
      });
    },
    handleUpdateShare(row){
      let title = '推荐'
      let isShare = 1;
      if(row.isShare == 1){
        title = '取消推荐'
        isShare = 0;
      }

      this.$confirm('是否确认' + title + '"' + row.title + '"？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  let params = {
                    detailId: row.detailId,
                    isShare: isShare
                  }
                  updateColumnDetail(params).then(res => {
                    this.getList();
                    this.$modal.msgSuccess(title + "成功");
                  });
                }).catch(() => {

                });
    },
    handleUpdateState(row, flag){
      let title = '发布'
      let state = 'Y'
      if(flag != 0){
        title = '下架'
        state = 'B'
      }
    this.$confirm('是否确认' + title + '"' + row.title + '"？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let params = {
                  detailId: row.detailId,
                  state: state,
                  userId: this.$store.state.user.id
                }
                updateColumnDetail(params).then(res => {
                  this.getList();
                  this.$modal.msgSuccess(title + "成功");
                });
              }).catch(() => {

              });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.isLbt == 1 && (this.form.picPath == null || this.form.picPath == '' || this.form.picPath.length == 0)){
            this.$modal.msg("当文章为轮播图时，必须上传导航图片");
            return false;
          }
          if (this.form.detailId != null) {
            updateColumnDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addColumnDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const detailIds = row.detailId || this.ids;
      this.$modal.confirm('是否确认删除文章内容详情编号为"' + detailIds + '"的数据项？').then(function() {
        return delColumnDetail(detailIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/columnDetail/export', {
        ...this.queryParams
      }, `columnDetail_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
